<script setup>
import { ref, onActivated, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getOrderDetail, payOrder, checkOrderPay } from '@/api/order'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const orderInfo = ref(null)
// 支付方式
const paymentMethod = ref('lianlpay_offline')

// 支付状态轮询定时器
let paymentCheckTimer = null

// 获取订单信息
const fetchOrderInfo = async () => {
  const orderId = route.path.split('/').pop()
  console.log('orderId:', orderId)

  if (!orderId) {
    ElMessage.error('订单ID不能为空')
    router.push('/order')
    return
  }

  loading.value = true
  try {
    const res = await getOrderDetail({ order_id: orderId })
    orderInfo.value = res.detail
    if (orderInfo.value.order_status !== '待支付') {
      // 0表示待付款状态
      ElMessage.warning('该订单不是待付款状态，无法进行支付')
      setTimeout(() => {
        router.push('/order')
      }, 2000)
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取订单信息
onActivated(() => {
  fetchOrderInfo()
})

// 检查支付状态
const checkPaymentStatus = async () => {
  if (!orderInfo.value?.order_bn) return

  try {
    const res = await checkOrderPay(orderInfo.value.order_bn)
    if (res.status === 'success') {
      // 支付成功
      ElMessage.success('支付成功')
      if (paymentCheckTimer) {
        clearInterval(paymentCheckTimer)
        paymentCheckTimer = null
      }
      setTimeout(() => {
        router.push('/order')
      }, 1500)
    }
  } catch (error) {
    console.error('检查支付状态失败:', error)
  }
}

// 处理支付
const handlePayment = async () => {
  if (!orderInfo.value || !orderInfo.value.order_bn) {
    ElMessage.error('订单信息不完整，无法完成支付')
    return
  }

  loading.value = true
  try {
    const res = await payOrder(orderInfo.value.order_bn, paymentMethod.value)
    if (res.gateway_url) {
      // 打开新窗口进行支付
      window.open(res.gateway_url, '_blank')
      ElMessage.success('正在跳转到支付页面...')

      // 开始轮询检查支付状态
      if (paymentCheckTimer) {
        clearInterval(paymentCheckTimer)
      }
      paymentCheckTimer = setInterval(checkPaymentStatus, 10000) // 每10秒检查一次
    } else {
      ElMessage.error('获取支付链接失败')
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (paymentCheckTimer) {
    clearInterval(paymentCheckTimer)
    paymentCheckTimer = null
  }
})

// 返回订单列表
const goBack = () => {
  if (paymentCheckTimer) {
    clearInterval(paymentCheckTimer)
    paymentCheckTimer = null
  }
  router.push('/order')
}
</script>

<template>
  <div class="payment-container" v-loading="loading">
    <div v-if="orderInfo" class="payment-content">
      <h2 class="payment-title">订单支付</h2>

      <div class="order-info">
        <div class="info-item">
          <span class="label">订单编号：</span>
          <span class="value">{{ orderInfo.order_bn }}</span>
        </div>
        <div class="info-item">
          <span class="label">订单金额：</span>
          <span class="value price">¥{{ orderInfo.amount }}</span>
        </div>
        <div class="info-item">
          <span class="label">下单时间：</span>
          <span class="value">{{ orderInfo.created_at }}</span>
        </div>
      </div>

      <div class="payment-methods">
        <h3>选择支付方式</h3>
        <div class="methods-list">
          <el-radio-group v-model="paymentMethod">
            <el-radio label="lianlpay_offline">连连支付-线下转账</el-radio>
          </el-radio-group>
        </div>
      </div>

      <div class="action-buttons">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="handlePayment">确认支付</el-button>
      </div>
    </div>

    <div v-else-if="!loading" class="empty-state">
      <el-empty description="未找到订单信息">
        <el-button @click="goBack">返回订单列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.payment-container {
  padding: 30px;

  .payment-content {
    max-width: 800px;
    padding: 30px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .payment-title {
    margin-bottom: 30px;
    font-size: 24px;
    color: #303133;
    text-align: center;
  }

  .order-info {
    padding: 20px;
    margin-bottom: 30px;
    background-color: #f8f8f8;
    border-radius: 4px;

    .info-item {
      display: flex;
      margin-bottom: 15px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 100px;
        color: #606266;
      }

      .value {
        flex: 1;
        color: #303133;

        &.price {
          font-weight: bold;
          color: #f56c6c;
        }
      }
    }
  }

  .payment-methods {
    margin-bottom: 30px;

    h3 {
      margin-bottom: 15px;
      font-size: 18px;
      color: #303133;
    }

    .methods-list {
      padding: 15px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
    }
  }

  .action-buttons {
    display: flex;
    gap: 20px;
    justify-content: center;
    margin-top: 30px;
  }

  .empty-state {
    display: flex;
    justify-content: center;
    padding: 50px 0;
  }
}
</style>
